// Copyright (c) 2020 Wang Zemin Personal. All Right Reserved

import * as React from "react";
import {Button, Card, Col, DatePicker, Form, Input, notification, Row, Select, Table} from "antd";
import {
    DeleteOutlined,
    FormOutlined,
    MessageOutlined,
    ReloadOutlined,
    SearchOutlined,
    SecurityScanOutlined,
    UserAddOutlined,
    UserOutlined
} from "@ant-design/icons";
import {Option} from "antd/es/mentions";
import {disableRole, fetchAllRole} from "../../requests/RoleManageRequest";
import CreateRoleModal from "../modals/CreateRoleModal";
import UpdateRoleModal from "../modals/UpdateRoleModal";
import DisableRoleModal from "../modals/DisableRoleModal";

// import CreateVerifyKeyModal from "./CreateVerifyKeyModal";

class RoleManagePage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            keys: [],
            selectedRowKey: "",
            selectedRolePermissions: [],
            pagination: {current: 1, pageSize: 10},
            searchFromRef: React.createRef(),
            isOwn: false,
            filters: {}
        };
    }

    componentDidMount = () => {
        this.refreshRoleData()
    }

    clickDisableRole = (e, roleName) => {
        console.log("Disable role with name:" + JSON.stringify(roleName))
        disableRole(roleName).then((edpKey) => {
            this.refreshRoleData()
            notification.info({message: "禁用激活码成功", description: "禁用激活码" + edpKey.result.roleName + "成功"});
        })

    }

    onTableChange = (pagination) => {
        this.setState({pagination: pagination}, ()=>this.refreshRoleData(this.state.filters));
    }

    refreshRoleData = (filters = {}) => {
        console.log("List all role ")
        fetchAllRole(this.state.pagination, filters)
            .then((roleDomains) => {
                let fetchKeys = roleDomains.result.map((roleDomain) => this.toRoleTableElement(roleDomain))
                this.setState({
                    keys: fetchKeys, pagination: {
                        current: roleDomains.pageNo,
                        pageSize: roleDomains.pageSize,
                        total: roleDomains.total
                    }
                })
            })
    }

    searchKeys = (filters) => {
        console.log("Begin to refresh data with filter:" + JSON.stringify(filters))
        this.setState({
            filters: filters,
            pagination: {current: 1, pageSize: 10}
        },()=> this.refreshRoleData(filters))

    }

    resetSearchKeys = () => {
        this.state.searchFromRef.current.resetFields();
    };


    toRoleTableElement = (roleDomain) => {
        return {
            "uuid": roleDomain.uuid,
            "roleName": roleDomain.roleName,
            "createTime": roleDomain.createTime,
            "createBy": roleDomain.createBy,
            "displayName": roleDomain.displayName,
            "description": roleDomain.description,
            "status": roleDomain.status,
            "permissions": roleDomain.permissions,
        }
    }

    toPermissionTableElement = (permissionDomain) => {
        return {
            "uuid": permissionDomain.uuid,
            "permissionName": permissionDomain.permissionName,
            "displayName": permissionDomain.displayName,
            "description": permissionDomain.description,
        }
    }


    createRole = () => {
        this.state.createRoleModal.showModal()
    }

    updateRole = () => {
        this.state.updateRoleModal.showModal()
    }

    disableRole = () => {
        this.state.disableRoleModal.showModal()
    }

    render = () => {
        let pagination = this.state.pagination

        const permissionColumns = [
            {
                title: '权限唯一标识',
                dataIndex: 'permissionName',
                key: 'permissionName',
            },
            {
                title: '权限显示名',
                dataIndex: 'displayName',
                key: 'displayName',
            },
            {
                title: '权限描述',
                dataIndex: 'description',
                key: 'description',
            },
        ]

        const roleColumns = [
            {
                title: '角色唯一标识',
                dataIndex: 'roleName',
                key: 'roleName',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
            },
            {
                title: '创建人',
                dataIndex: 'createBy',
                key: 'createBy',
            },
            {
                title: '角色显示名',
                dataIndex: 'displayName',
                key: 'displayName',
            },
            {
                title: '角色描述信息',
                dataIndex: 'description',
                key: 'description',
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (text, record, index) => (
                    <Button type="dashed" danger disabled={record.status !== "NORMAL"}
                            key={record.keyName}>{record.status}</Button>
                ),
            }]

        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                let permissions = selectedRows[0].permissions.map((pDomain) => this.toPermissionTableElement(pDomain))
                console.log(`Current selected keys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({
                    selectedRolePermissions: permissions,
                    selectedRowKey: selectedRows[0].roleName,
                    selectedRole : selectedRows[0],
                })
            }
        };


        return (
            <div style={{padding: 10, margin: 10}}>
                <Card title="角色搜索条件">
                    <Form name="basic" ref={this.state.searchFromRef} layout="inline" onFinish={this.searchKeys}
                          style={{marginTop: 10, marginBottom: 10, width: '100%', border: "1", borderColor: "#000000"}}>

                        <Row style={{width: '100%'}}>
                            <Col span={8} offset={1}>
                                <Form.Item name="roleName">
                                    <Input prefix={<SecurityScanOutlined/>} placeholder="角色唯一标识"
                                           style={{width: '98%'}}/>
                                </Form.Item>
                            </Col>
                            <Col span={3} offset={1}>
                                <Form.Item name="createBy" style={{width: '95%'}}>
                                    <Input prefix={<UserOutlined/>} placeholder="角色创建者"/>
                                </Form.Item>
                            </Col>
                            <Col span={6} offset={1}>
                                <Form.Item name="createTimeRange" style={{width: '95%'}}>
                                    <DatePicker.RangePicker placeholder={["创建时间", "创建时间"]}/>
                                </Form.Item>
                            </Col>

                        </Row>
                        <Row style={{width: '100%'}}>
                            <Col span={3} offset={1}>
                                <Form.Item name="displayName" style={{width: '95%', marginTop: 20}}>
                                    <Input prefix={<UserOutlined/>} placeholder="显示名称"/>
                                </Form.Item>
                            </Col>


                            <Col span={4} offset={1}>
                                <Form.Item name="description" style={{width: '95%', marginTop: 20}}>
                                    <Input prefix={<MessageOutlined/>} placeholder="描述信息"/>
                                </Form.Item>
                            </Col>

                            <Col span={3} offset={1}>
                                <Form.Item name="roleStatus" style={{marginTop: 20}}>
                                    <Select placeholder="状态" allowClear>
                                        <Option value="NORMAL">正常</Option>
                                        <Option value="DISABLE">禁用</Option>
                                    </Select>
                                </Form.Item>
                            </Col>

                            <Col span={2} offset={1}>
                                <Form.Item style={{marginTop: 20}}>
                                    <Button type="primary" icon={<SearchOutlined/>} htmlType="submit"
                                            style={{backgroundColor: "#13ce66"}}>搜索</Button>
                                </Form.Item>
                            </Col>
                            <Col span={2}>
                                <Form.Item style={{marginTop: 20}}>
                                    <Button type="primary" icon={<ReloadOutlined/>} onClick={this.resetSearchKeys}
                                            style={{backgroundColor: "#ffba00"}}>重置</Button>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>

                </Card>

                <Row>
                    <Card title="角色列表" style={{marginTop: 30, marginBottom: 10}}>
                        <Row  style={{marginBottom: 10}}>
                            <Col span={4} offset={1}>
                                <Button type="primary" icon={<UserAddOutlined/>}
                                        style={{backgroundColor: "#13ce66"}} onClick={this.createRole}>新增</Button>
                            </Col>
                            <Col span={4}>
                                <Button type="primary" icon={<FormOutlined/>}
                                        style={{backgroundColor: "#1890ff"}} disabled={this.state.selectedRowKey === ""}
                                        onClick={this.updateRole}>修改</Button>
                            </Col>
                            <Col span={4}>
                                <Button type="primary" icon={<DeleteOutlined/>}
                                        style={{backgroundColor: "#ffa4a4"}} disabled={this.state.selectedRowKey === ""}
                                        onClick={this.disableRole}>禁用</Button>
                            </Col>
                        </Row>
                        <Table
                            rowSelection={{
                                type: "radio",
                                ...rowSelection
                            }}
                            columns={roleColumns}
                            dataSource={this.state.keys}
                            rowKey={(record) => record.uuid}
                            onChange={this.onTableChange}
                            pagination={pagination}
                            size="small"
                        />

                    </Card>

                    <Col span={6} offset={1}>
                        <Card title="角色拥有的权限列表" style={{marginTop: 30, marginBottom: 10}}>
                            <Table
                                columns={permissionColumns}
                                dataSource={this.state.selectedRolePermissions}
                                rowKey={(record) => record.uuid}
                                size="small"
                            />
                        </Card>
                    </Col>
                </Row>


                <CreateRoleModal onRef={(ref) => {
                    this.setState({createRoleModal: ref})
                }}/>

                <UpdateRoleModal onRef={(ref) => {
                    this.setState({updateRoleModal: ref})
                }} roleName={this.state.selectedRowKey}  role={this.state.selectedRole}/>

                <DisableRoleModal onRef={(ref) => {
                    this.setState({disableRoleModal: ref})
                }} roleName={this.state.selectedRowKey}/>
            </div>
        );
    }

}

export default RoleManagePage